import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 25397
 * Date: 2021-12-27
 * Time: 9:45
 */
//服务端
public class TcpServerDemo {
    public static void main(String[] args) throws IOException {
        ServerSocket serverSocket=null;//不直接在try里面写是为了提升作用域，不然无法在finally里面关闭
        Socket socket=null;
        InputStream inputStream=null;
        ByteArrayOutputStream baos=null;
        try{
            //1.服务器有一个地址
             serverSocket=new ServerSocket(9999);
            //2.等待客户端链接
             socket=serverSocket.accept();
            //3.读取客户端的消息
             inputStream=socket.getInputStream();

           /* byte[]buffer=new byte[100];
            int len;
            while((len=inputStream.read(buffer))!=-1){
                String msg=new String(buffer,0,len);

            }*/

            //管道流
             baos=new ByteArrayOutputStream();
            byte[]buffer=new byte[100];
            int len;
            while((len=inputStream.read(buffer))!=-1){
                baos.write(buffer,0,len);
            }


        }catch(IOException e){
            e.printStackTrace();
        }finally {
            //关闭流，先开后关
            baos.close();
            inputStream.close();
            socket.close();
            serverSocket.close();
        }
    }

}
